package com.rtzh.learnkotlin.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.rtzh.learnkotlin.R
import com.rtzh.learnkotlin.bean.Msg

/**
 * 消息adapter
 */
class MsgAdapter(val msgList: List<Msg>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    //设置布局的方法
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        if (viewType == Msg.TYPE_RECEIVED) {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.msg_left_item, parent, false)
            LeftViewHolder(view)
        } else {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.msg_right_item, parent, false)
            RightViewHolder(view)
        }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val msg=msgList[position];
        when(holder){
            is LeftViewHolder ->holder.leftmsg.text=msg.content
            is RightViewHolder -> holder.rightmsg.text=msg.content
            else ->throw IllegalArgumentException()
        }
    }

    override fun getItemViewType(position: Int): Int {
        val msg = msgList[position]
        return msg.type
    }

    inner class LeftViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val leftmsg: TextView = view.findViewById(R.id.leftMsg)

    }

    inner class RightViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val rightmsg: TextView = view.findViewById(R.id.rightMsg)

    }

    override fun getItemCount(): Int = msgList.size


}